package com.imcrl.component.dock
{
	import com.imcrl.component.ext.Sprite;
	import com.imcrl.core.IResizeable;
	
	import flash.geom.Point;
	import flash.geom.Rectangle;
	
	import starling.display.Image;
	import starling.events.EnterFrameEvent;
	import starling.events.Touch;
	import starling.events.TouchEvent;
	import starling.events.TouchPhase;

	public class Dock extends Sprite implements IResizeable
	{
		private var itemPad:int=110;
		private var len:int=5;
		private var icons:Vector.<DockItem>;
		public function Dock()
		{
			super();
			
			icons=new Vector.<DockItem>();
			
			var s:DockItem
			for(var i:int=0;i<len;i++){
				s=new DockItem();
				
				s.xo=s.x=itemPad*i;
				
				
				this.addChild(s);
				icons.push(s);
			}
			
			rect=this.getBounds(this);
			
			this.addEventListener(TouchEvent.TOUCH,mouseHandler);
		}
		
		private var isMouseDown:Boolean=false;
		private function mouseHandler(event:TouchEvent):void{
			var touch:Touch=event.getTouch(this);
			switch(touch.phase){
				case TouchPhase.HOVER :
					this.addEventListener(EnterFrameEvent.ENTER_FRAME,enterHandler);
					break;
				case TouchPhase.BEGAN :
					isMouseDown=true;
					break;
				case TouchPhase.ENDED :
					isMouseDown=false;
					break;
			}
		}
		
		
		private var rect:Rectangle;
		private function enterHandler(touch:Touch):void{
			var m:Point=touch.getLocation(this);
			var mx:int=m.x;
			var my:int=m.y;
			
			var s:Number=0;
			var newx:int;
			
			//trace("e");
			rect=this.getBounds(this);
			
			var item:DockItem;
			
			var stopLen:int=0;
			if(mx<rect.left || mx>rect.right || my<rect.top || my>rect.bottom){
				
				for each(item in icons){
					s=item.scaleX+(1-item.scaleX)/3;
					
					newx=item.x+(item.xo-item.x)/3;
					item.scaleX=item.scaleY=s;
					
					item.x=newx;
					
					
					if(Math.abs(1-item.scaleX)<0.05 && Math.abs(item.x-item.xo)<0.05){
						isMouseDown=false;
					}
				}

				
				return;
			}
			
			var dx:int;
			var dy:int;
			
			var scaleV:int=itemPad*2;
			var r:int=3/4*itemPad;
			
			var sin:Number;
			for each(item in icons){
				dx=item.xo-mx;
				
				s=(scaleV-Math.abs(dx))/100;
				if(s<1){
					s=1;
				}
				
				
				s=item.scaleX+(s-item.scaleX)/3;
				item.scaleX=item.scaleY=s;
				
				//if(dx)
				sin=dx/Math.sqrt(dx*dx+r*r);
				//trace(sin);
				newx=item.x+(item.xo+sin*r-item.x)/3;
				
				item.x=newx;
			}
			
			//trace("================")
			
			
			
		}
		
		
		public function resize(w:int,h:int):void{
			this.x=(w-width)>>1;
			this.y=h;
		}
		
	}
}